<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>html2canvas截图</title>
    <style type="text/css">
        .content{
          display: block;
          position: relative;
          width: 300px;
          height: 300px;
          background-color: #E6B246
        }
        table{
          border:1px solid #F00
        }
        table td {
          border:1px solid #F00
        }
        #imgDiv{
            background-color: #00ee00;
        }
        #btn{
            padding: 10px;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div id="imgDiv">
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td>ces</td>
                <td>ces</td>
            </tr>
            <tr>
                <td>ces</td>
                <td>ces</td>
            </tr>
        </table>
        <div class="content" >测试</div>
    </div>
    <button id="btn">保存为图片</button>
</body>
</html>
<script src="../../lib/jquery/3.6.0/jquery-3.6.0.min.js"></script>
<!-- 让全部浏览器都支持 ES6 Promise 对象 -->
<script src="../../lib/bluebird/bluebird.min.js"></script>
<script src="../../lib/html2canvas/html2canvas.min.js"></script>
<script type="text/javascript">
    // 初始化方法
    $(document).ready(function(){
        // 添加点击事件
        $("#btn").on("click", function () {

            var canvas = createCanvas("imgDiv");
            var scale = getPixelRatio(canvas.getContext('2d'));

            var shareContent = document.getElementById("imgDiv");
            var width = shareContent.offsetWidth;
            var height = shareContent.offsetHeight;

            // html2canvas配置项
            var opts = {
                // 是否允许跨原点图像污染画布
                allowTaint: false,
                useCORS: true,
                // 设置像素比
                scale: scale,
                // 添加画布
                canvas: canvas,
                // 设置宽高
                width: width,
                height: height,
                // 设备像素比
                dpi: window.devicePixelRatio
            };
            // 执行html2canvas方法
            html2canvas(document.getElementById("imgDiv"), opts).then(function (canvas) {
                // 将canvas对象转换为base64位编码
                var dataUrl = canvas.toDataURL('image/jpeg', 1.0);
                console.log("dataUrl",dataUrl);
                // 生成的图片名称
                // 方式一：base64下载
                downloadImageByBase64(dataUrl,"Base64图片.jpg");
                // 方式一：Blob下载
                /*var blobUrl = dataURIToBlob(dataUrl);
                downloadBlob("Blob图片.jpg",blobUrl);*/
            });
        });
    })

    /**
     * 创建画布对象
     * @param idName
     * @returns {HTMLCanvasElement}
     */
    function createCanvas(idName){
        // 获取截取内容的宽高
        var shareContent = document.getElementById(idName);
        var width = shareContent.offsetWidth;
        var height = shareContent.offsetHeight;
        // 创建画布元素
        var canvas = document.createElement("canvas");
        var context = canvas.getContext('2d');
        // 设置启用图像平滑
        context.imageSmoothingEnabled = false;
        // 设置启用 webkit 图像平滑
        context.webkitImageSmoothingEnabled = false;
        // 设置ms 图像平滑已启用
        context.msImageSmoothingEnabled = false;
        // 设置启用图像平滑
        context.imageSmoothingEnabled = false;

        // 将canvas的容器扩大PixelRatio倍，再将画布缩放，将图像放大PixelRatio倍。
        var scale = getPixelRatio(context);
        canvas.width = width * scale;
        canvas.height = height * scale;
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        // 设置缩放比例
        context.scale(scale, scale);
        return canvas;
    }

    /**
     * 获取设备的PixelRatio（像素比）
     * @param context
     * @returns {number}
     */
    function getPixelRatio(context) {
        var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio ||
            context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio ||
            context.oBackingStorePixelRatio || context.backingStorePixelRatio || 0.5;
        return (window.devicePixelRatio || 0.5) / backingStore;
    };

    /**
     * 编辑自 https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill
     * 将Base转Blob
     * @param dataURI
     */
    function dataURIToBlob(dataURI) {
        // window.atob() 方法用于解码使用 base-64 编码的字符串
        var binStr = atob(dataURI.split(',')[1]);
        var len = binStr.length;
        // 创建一个类型是Uint8，长度为的len数组
        var arr = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            // 将binStr写入arr
            arr[i] = binStr.charCodeAt(i);
        }
        return new Blob([arr]);
    }

    /**
     * 下载Blob类型数据
     * @param imgName
     * @param blob
     */
    function downloadBlob(imgName, blob) {
        // 创建a标签，添加href属性
        var triggerDownload = $("<a>").attr("href",
            // 创建对象 URL,添加download属性，附加到body上，并添加点击事件
            URL.createObjectURL(blob)).attr("download", imgName).appendTo("body").on("click", function () {
                // navigator.msSaveBlob方法允许用户在客户端上保存文件，方法如同从 Internet 下载文件
                if (navigator.msSaveBlob) {
                    return navigator.msSaveBlob(blob, imgName);
                }
            });
        // 触发事件
        triggerDownload[0].click();
        // 删除标签
        triggerDownload.remove();
    };

    function downloadImageByBase64(url,fileName) {
        let link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", fileName);
        link.click();
    }
</script>